﻿using DKPScoreWebApi.DTOs.Requests;
using DKPScoreWebApi.DTOs.Results;
using DKPScoreWebApi.Models;
using DKPScoreWebApi.Services.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DKPScoreWebApi.Controllers
{
    /// <summary>
    /// 工会管理控制器
    /// 处理工会相关的所有请求，包括创建、查询、更新、删除等操作
    /// </summary>
    [ApiController]
    [Route("api/guilds")]
    public class GuildsController : ControllerBase
    {
        private readonly IGuildService _guildService;
        private readonly IMemberService _memberService;
        private readonly IDkpService _dkpService;
        private readonly ILogger<GuildsController> _logger;

        /// <summary>
        /// 构造函数，依赖注入相关服务
        /// </summary>
        public GuildsController(IGuildService guildService, IMemberService memberService, IDkpService dkpService, ILogger<GuildsController> logger)
        {
            _guildService = guildService;
            _memberService = memberService;
            _dkpService = dkpService;
            _logger = logger;
        }

        /// <summary>
        /// 创建新工会接口
        /// POST /api/guilds?userId=123
        /// </summary>
        /// <param name="userId">创建者用户ID</param>
        /// <param name="request">创建工会请求数据</param>
        /// <returns>创建的工会信息</returns>
        [HttpPost]
        public async Task<ActionResult<ApiResult<Guild>>> CreateGuild(int userId, [FromBody] CreateGuildRequest request)
        {
            try
            {
                // 调用服务创建工会
                var guild = await _guildService.CreateGuildAsync(userId, request);
                return Ok(new ApiResult<Guild> { Success = true, Data = guild });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工会失败");
                return BadRequest(new ApiResult { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户管理的工会列表接口
        /// GET /api/guilds?userId=123
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>用户管理的工会列表</returns>
        [HttpGet]
        public async Task<ActionResult<ApiResult<List<Guild>>>> GetMyGuilds(int userId)
        {
            try
            {
                var guilds = await _guildService.GetUserGuildsAsync(userId);
                return Ok(new ApiResult<List<Guild>> { Success = true, Data = guilds });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户工会失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取工会列表失败" });
            }
        }

        /// <summary>
        /// 获取工会详情接口
        /// GET /api/guilds/{guildId}?userId=123
        /// </summary>
        /// <param name="userId">当前用户ID</param>
        /// <param name="guildId">工会ID</param>
        /// <returns>工会详情，包含成员、统计和排名信息</returns>
        [HttpGet("{guildId}")]
        public async Task<ActionResult<ApiResult<object>>> GetGuildDetail(int userId, int guildId)
        {
            try
            {
                // 检查用户权限
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                // 获取工会基本信息
                var guild = await _guildService.GetGuildByIdAsync(guildId);

                // 获取工会成员列表
                var members = await _memberService.GetGuildMembersAsync(guildId);

                // 获取工会统计信息
                var stats = await _guildService.GetGuildStatsAsync(guildId);

                // 获取工会排名信息（前10名）
                var ranking = await _dkpService.GetGuildRankingAsync(guildId, 10);

                // 返回完整的工会详情
                return Ok(new ApiResult<object>
                {
                    Success = true,
                    Data = new
                    {
                        Guild = guild,
                        Members = members,
                        Stats = stats,
                        Ranking = ranking
                    }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工会详情失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取工会详情失败" });
            }
        }

        /// <summary>
        /// 更新工会信息接口
        /// PUT /api/guilds/{guildId}?userId=123
        /// </summary>
        /// <param name="userId">当前用户ID</param>
        /// <param name="guildId">工会ID</param>
        /// <param name="request">更新请求数据</param>
        /// <returns>操作结果</returns>
        [HttpPut("{guildId}")]
        public async Task<ActionResult<ApiResult>> UpdateGuild(int userId, int guildId, [FromBody] CreateGuildRequest request)
        {
            try
            {
                // 检查用户权限
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                // 调用服务更新工会信息
                var success = await _guildService.UpdateGuildAsync(guildId, request);
                if (!success)
                    return NotFound(new ApiResult { Success = false, Message = "工会不存在" });

                return Ok(new ApiResult { Success = true, Message = "更新成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工会失败");
                return BadRequest(new ApiResult { Success = false, Message = "更新工会失败" });
            }
        }

        /// <summary>
        /// 删除工会接口
        /// DELETE /api/guilds/{guildId}?userId=123
        /// </summary>
        /// <param name="userId">当前用户ID</param>
        /// <param name="guildId">工会ID</param>
        /// <returns>操作结果</returns>
        [HttpDelete("{guildId}")]
        public async Task<ActionResult<ApiResult>> DeleteGuild(int userId, int guildId)
        {
            try
            {
                // 检查用户权限
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限操作此工会" });

                // 调用服务删除工会（软删除）
                var success = await _guildService.DeleteGuildAsync(guildId);
                if (!success)
                    return NotFound(new ApiResult { Success = false, Message = "工会不存在" });

                return Ok(new ApiResult { Success = true, Message = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除工会失败");
                return BadRequest(new ApiResult { Success = false, Message = "删除工会失败" });
            }
        }

        /// <summary>
        /// 获取工会统计信息接口
        /// GET /api/guilds/{guildId}/stats?userId=123
        /// </summary>
        /// <param name="userId">当前用户ID</param>
        /// <param name="guildId">工会ID</param>
        /// <returns>工会统计信息</returns>
        [HttpGet("{guildId}/stats")]
        public async Task<ActionResult<ApiResult<GuildStats>>> GetGuildStats(int userId, int guildId)
        {
            try
            {
                // 检查用户权限
                if (!await _guildService.IsUserGuildAdminAsync(userId, guildId))
                    return Unauthorized(new ApiResult { Success = false, Message = "无权限访问此工会" });

                // 获取工会统计信息
                var stats = await _guildService.GetGuildStatsAsync(guildId);
                return Ok(new ApiResult<GuildStats> { Success = true, Data = stats });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工会统计失败");
                return BadRequest(new ApiResult { Success = false, Message = "获取统计失败" });
            }
        }
    }

    /// <summary>
    /// 添加工会管理员请求数据模型
    /// </summary>
    public class AddGuildAdminRequest
    {
        /// <summary>
        /// 目标用户ID
        /// </summary>
        public int TargetUserId { get; set; }

        /// <summary>
        /// 管理员角色，默认为admin
        /// </summary>
        public string Role { get; set; } = "admin";
    }
}
